package net.lab1024.smartadmin.module.business.tourist.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.lab1024.smartadmin.common.constant.ResponseCodeConst;
import net.lab1024.smartadmin.common.domain.PageResultDTO;
import net.lab1024.smartadmin.common.domain.ResponseDTO;
import net.lab1024.smartadmin.common.heartbeat.StringUtil;
import net.lab1024.smartadmin.module.business.tourist.dao.TouristDao;
import net.lab1024.smartadmin.module.business.tourist.domain.dto.TouristAddDTO;
import net.lab1024.smartadmin.module.business.tourist.domain.dto.TouristUpdateDTO;
import net.lab1024.smartadmin.module.business.tourist.domain.dto.TouristQueryDTO;
import net.lab1024.smartadmin.module.business.tourist.domain.entity.TouristEntity;
import net.lab1024.smartadmin.module.business.tourist.domain.vo.TouristVO;
import net.lab1024.smartadmin.module.business.tourist.domain.vo.TouristExcelVO;
import net.lab1024.smartadmin.util.SmartHttpUtil;
import net.lab1024.smartadmin.util.SmartPageUtil;
import net.lab1024.smartadmin.util.SmartBeanUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * [  ]
 *
 * @author wldd
 * @version 1.0
 * @company 游客
 * @copyright (c)  游客Inc. All rights reserved.
 * @date 2020-12-28 19:40:01
 * @since JDK1.8
 */
@Service
public class TouristService {

    @Autowired
    private TouristDao touristDao;

    /**
     * 根据id查询
     */
    public TouristEntity getById(Long id){
        return  touristDao.selectById(id);
    }

    /**
     * 分页查询
     * @author wldd
     * @date 2020-12-28 19:40:01
     */
    public ResponseDTO<PageResultDTO<TouristVO>> queryByPage(TouristQueryDTO queryDTO) {
        Page page = SmartPageUtil.convert2QueryPage(queryDTO);
        IPage<TouristVO> voList = touristDao.queryByPage(page, queryDTO);
        PageResultDTO<TouristVO> pageResultDTO = SmartPageUtil.convert2PageResult(voList);
        return ResponseDTO.succData(pageResultDTO);
    }

    /**
     * 添加
     * @author wldd
     * @date 2020-12-28 19:40:01
     */
    public ResponseDTO<String> add(TouristAddDTO addDTO) {
        TouristEntity entity = SmartBeanUtil.copy(addDTO, TouristEntity.class);
        touristDao.insert(entity);
        return ResponseDTO.succ();
    }

    /**
     * 编辑
     * @author wldd
     * @date 2020-12-28 19:40:01
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> update(TouristUpdateDTO updateDTO) {
        TouristEntity entity = SmartBeanUtil.copy(updateDTO, TouristEntity.class);
        touristDao.updateById(entity);
        return ResponseDTO.succ();
    }

    /**
     * 删除
     * @author wldd
     * @date 2020-12-28 19:40:01
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> deleteByIds(List<Long> idList) {
        touristDao.deleteByIdList(idList);
        return ResponseDTO.succ();
    }

    /**
     * 查询全部导出对象
     * @author wldd
     * @date 2020-12-28 19:40:01
     */
    public List<TouristExcelVO> queryAllExportData(TouristQueryDTO queryDTO) {
        return touristDao.queryAllExportData( queryDTO);
    }

    /**
     * 批量查询导出对象
     * @author wldd
     * @date 2020-12-28 19:40:01
     */
    public List<TouristExcelVO> queryBatchExportData(List<Long> idList) {
        return touristDao.queryBatchExportData(idList);
    }

    /**
     * 根据code添加旅客信息
     * @param code wx code
     * @return
     */
    public ResponseDTO<String> addTouristByCode(String code) {
        Map<String,String> param  = new HashMap<>();
        param.put("appid","wx1c4ff64d091fbaee");
        param.put("secret","76c4b024920d905ac292a413d8f56e6b");
        param.put("code",code);
        param.put("grant_type","authorization_code");

        String result = "";
        try {
            result = SmartHttpUtil.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", param, null);
            JSONObject jsonObject = JSON.parseObject(result);
            String accessToken = (String) jsonObject.get("access_token");
            String openId =  (String) jsonObject.get("openid");
            System.out.println(result);
//            拉取用户信息(需scope为 snsapi_userinfo)
            if(StringUtils.isNotEmpty(accessToken)) {
                System.out.println("进来了.......");
                Map<String,String> paramInfo  = new HashMap<>();
                paramInfo.put("access_token",accessToken);
                paramInfo.put("openid",openId);
                paramInfo.put("lang","zh_CN");
                result = SmartHttpUtil.sendGet("https://api.weixin.qq.com/sns/userinfo", paramInfo, null);
                System.out.println("UserResult---" + result);
                JSONObject userInfoJson = JSON.parseObject(result);
                String nickName = (String) userInfoJson.get("nickname");
                String headImgUrl = (String) userInfoJson.get("headimgurl");
                //先查询openid ，查看用户是否已存在
                QueryWrapper<TouristEntity> touristEntityQueryWrapper = new QueryWrapper<>();
                touristEntityQueryWrapper.lambda().eq(TouristEntity::getOpenId,openId);
                Integer isExit = this.touristDao.selectCount(touristEntityQueryWrapper);
                if(isExit <= 0) {
                    //添加旅客
                    TouristEntity touristEntity = new TouristEntity();
                    touristEntity.setOpenId(openId);
                    touristEntity.setAvatar(headImgUrl);
                    touristEntity.setUserNickName(nickName);
                    touristEntity.setStatus(1);
                    this.touristDao.insert(touristEntity);
                }
            } else {
                return ResponseDTO.wrap(ResponseCodeConst.ERROR_PARAM).setMsg("请重新认证..");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("--------result" + result);


        return ResponseDTO.succ();
    }
}
